/**
 * Created by Mark_ren on 2016/11/28.
 * 苟富贵,無相忘
 */
var moment = require("moment");
var co = require('co');
var formidable = require('formidable');
var fs = require('fs');
var seqModule = require('../../../routes/createModules');
var seq = new seqModule();
var util = require('../../../common/util');


var pfMemberController = {
    getPfMemberPage: function (req, res) {
        co(function () {
            var page = parseInt(req.query.page);
            var params = {};
            var paramT = {};
            //模糊查询
            if (req.query.pTitle != undefined) {
                params["$or"] = [{ "name": { "$like": "%" + req.query.pTitle + "%" } }, { "tel": { "$like": "%" + req.query.pTitle + "%" } }, { "hospitalName": { "$like": "%" + req.query.pTitle + "%" } }];
            }
            if (req.query.meetNum != undefined) {
                params["meetNum"] = req.query.meetNum;
            }
            if (req.query.type != undefined) {
                params["type"] = parseInt(req.query.type);
            }
            paramT["where"] = params;
            paramT["order"] = [["createTime", 'DESC']];
            if (req.query.page != undefined && req.query.rows != undefined) {
                paramT["offset"] = parseInt(req.query.page);
                paramT["limit"] = parseInt(req.query.rows);
            }
            seq.pfMemberModule.findAndCountAll(paramT).then(function (result) {
                res.json({ "success": true, "page": page, "total": result.count, "result": result.rows });
            });
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(e);
        })
    },
    getPfMemberById: function (req, res) {
        co(function () {
            seq.pfMemberModule.findOne({ where: req.params }).then(function (qdMeet) {
                res.json({ 'success': true, 'msg': '查询成功', 'result': qdMeet });
            })
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '添加失败' });
            console.log(e);
        })
    },
    addPfMember: function (req, res) {
        co(function () {
            req.body.id = util.getUUID().replace(/-/g, "");
            req.body.createTime = util.getNowTime();
            seq.pfMemberModule.create(req.body).then(function (qdMeet) {
                res.json({ 'success': true, 'msg': '添加成功' });
            })
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '添加失败' });
            console.log(e);
        })
    },
    updatePfMember: function (req, res) {
        co(function () {
            seq.pfMemberModule.update(req.body, { where: req.params }).then(function (qdMeet) {
                res.json({ 'success': true, 'msg': '修改成功' });
            })
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '修改失败' });
            console.log(e);
        })
    },
    deletePfMember: function (req, res) {
        co(function () {
            var params = req.query.params;
            var arr = params.split(",");
            var paramT = [arr];
            seq.pfMemberModule.destroy({ where: { id: paramT } }).then(function (qdMeet) {
                res.json({ 'success': true, 'msg': '删除成功' });
            })
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '删除失败' });
            console.log(e);
        })
    },
    addPfMemberForm: function (req, res, next) {
        co(function () {
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/expertImg";
                form.type = true;
                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields, files) {
                    // res.render('index', { paths: [files.upload.name] });
                    if (files.headImg != null && files.headImg.name != "") {
                        var imgType = files.headImg.name.split(".");
                        files.headImg.name = "pfMember" + moment().format("YYYYMMDDHHmmss") + "." + imgType[imgType.length - 1];
                        fs.renameSync(files.headImg.path, form.uploadDir + "/" + files.headImg.name);
                        fields["headImg"] = files.headImg.name;
                    }
                    var meetNum = req.params.meetNum;
                    var type = req.params.type;
                    fields.meetNum = meetNum;
                    fields.type = type;
                    fields.id = util.getUUID().replace(/-/g, "");
                    fields.createTime = util.getNowTime();
                    seq.pfMemberModule.create(fields).then(function (qdMeet) {
                        res.redirect(util.getIP() + "pfMeet/pfMemberPlayerList.html?meetNum=" + meetNum + "&type=" + type);
                    })
                });
            }
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '删除失败' });
            console.log(e);
        })
    },
    updatePfMemberForm: function (req, res, next) {
        co(function () {
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/expertImg";
                form.type = true;

                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields, files) {
                    // res.render('index', { paths: [files.upload.name] });
                    if (files.headImg != null && files.headImg.name != "") {
                        var imgType = files.headImg.name.split(".");
                        files.headImg.name = "pfMember" + moment().format("YYYYMMDDHHmmss") + "." + imgType[imgType.length - 1];
                        fs.renameSync(files.headImg.path, form.uploadDir + "/" + files.headImg.name);
                        fields["headImg"] = files.headImg.name;
                    }
                    var meetNum = req.params.meetNum;
                    var type = req.params.type;
                    var id = req.params.id;
                    seq.pfMemberModule.update(fields, { where: { id: id } }).then(function (qdMeet) {
                        res.redirect(util.getIP() + "pfMeet/pfMemberPlayerList.html?meetNum=" + meetNum + "&type=" + type);
                    })
                });
            }
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '删除失败' });
            console.log(e);
        })
    },
    getPfPlayerScore: function (req, res, next) {
        co(function () {
            var meetNum = req.params.meetNum;
            var type = req.params.type;
            var sql = "select meet.id,meet.head_img as headImg,meet.name,meet.tel,meet.hospital_name as hospitalName,meet.create_time as createTime,(select avg(total_score) from pf_total_score where player_id = meet.id) as totalScore from pf_member as meet where 1=1 ";
            sql += " and meet.meet_num = '" + meetNum + "' and meet.type = " + type;
            seq.sequelize.query(sql).spread(function (result) {
                res.json({ 'success': true, 'msg': '查询成功', 'result': result });
            })
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(e);
        })
    }
}
module.exports = pfMemberController;